package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.annotation.RequiredPermission;
import cn.wolfcode.rbac.domain.Permission;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private ApplicationContext ctx;
    @Autowired
    private PermissionMapper mapper;

    @Override
    public void reload() {
        //获取容器中贴了Controller的bean
        //查出所有数据库中已有的所有权限表达式
        List<String> exps = mapper.getAllExpression();
        Map<String, Object> map = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> ctrls = map.values();
        for (Object ctrl : ctrls) {
            Method[] methods = ctrl.getClass().getDeclaredMethods();
            for (Method method : methods) {
                RequiredPermission anno = method.getAnnotation(RequiredPermission.class);
                if (anno != null && !exps.contains(anno.value()[1])) {
                    String name = anno.value()[0];
                    String expression = anno.value()[1];
                    Permission permission = new Permission(name, expression);
                    mapper.insert(permission);
                }
            }
        }


    }


    @Override
    public void saveOrUpdate(Permission permission) {

    }

    @Override
    public void delete(Long id) {

    }

    @Override
    public Permission get(Long id) {
        return null;
    }

    @Override
    public PageResult query(QueryObject qo) {
        int rows = mapper.getCount();
        if (rows == 0) {
            return new PageResult(qo.getPageSize());
        }
        List<Permission> list = mapper.selectAll(qo);
        return new PageResult(qo.getCurrentPage(), qo.getPageSize(), rows, list);
    }

    @Override
    public List<Permission> getAll() {

        return mapper.getAll();
    }


}
